"""
涉及AES加解密内容
以及base64内容
"""
import json
import re
import base64
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend


# js字节数组转16进制文本
def convert_words_to_bytes(words, sigBytes):
    byte_array = []
    for word in words:
        byte_array.append((word >> 24) & 0xFF)
        byte_array.append((word >> 16) & 0xFF)
        byte_array.append((word >> 8) & 0xFF)
        byte_array.append(word & 0xFF)
    # 截取有效字节
    return bytes(byte_array[:sigBytes])


# 返回base64解码文本
def base64_encrypt(text):
    return base64.b64encode(text).decode('utf-8')


# 从加密的url中，获取加密内容
def AES_Cipher_from_book(url=None):
    key_data = {"words": [825307441, 825307441, 825307441, 825307441], "sigBytes": 16}

    if not url:
        url = input('输入URL：')
    index = url.find('bookDetail?')
    base64_str = url[index + len('bookdetail?')::]
    base64_str = base64.b64decode(base64_str).decode('utf-8')
    base64_str = json.loads(base64_str)
    ciphertext_b64 = base64_str['encrypt']
    iv_data = base64_str['iv']

    key = convert_words_to_bytes(key_data["words"], key_data["sigBytes"])
    iv = convert_words_to_bytes(iv_data["words"], iv_data["sigBytes"])

    # 解码 base64
    ciphertext = base64.b64decode(ciphertext_b64)
    # 无填充模式
    try:
        data = {
            'key': key,
            'iv': iv,
            'ciphertext': ciphertext,
        }
        plain_text = AES_decrypt(data)
        de = plain_text.rstrip(b'\x00').decode('utf-8', errors='ignore')
        # print(de)
        numbers = re.findall(r'\d+', de)
        book_id = numbers[0]
        eisbn = numbers[1]

        return book_id, eisbn
    except ValueError:
        print("填充错误，可能是密钥、IV 或加密模式不正确。")


# AES加密中，使用此填充
def pkcs7_pad(data, block_size=16):
    """
    对数据进行PKCS#7填充。
    :param data: 需要填充的字节串。
    :param block_size: 块大小（默认是16字节）。
    :return: 填充后的字节串。
    """
    padding_length = block_size - (len(data) % block_size)
    padding = bytes([padding_length] * padding_length)
    return data + padding


# AES加密，使用pkcs7填充
def AES_encrypt(data):
    key = data['key']
    iv = data['iv']
    plaintext = data['plaintext']

    # 对明文进行PKCS#7填充
    padded_plaintext = pkcs7_pad(plaintext)

    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
    encryptor = cipher.encryptor()
    ct_bytes = encryptor.update(padded_plaintext) + encryptor.finalize()
    base64_str = base64.b64encode(ct_bytes).decode('utf-8')
    return base64_str


# 解密，不填充，手动移除填充
def AES_decrypt(data):
    # key_data = {"words": [539897450, 2979453134, 2318141273, 526924706], "sigBytes": 16}
    # key = convert_words_to_bytes(key_data["words"], key_data["sigBytes"])
    key = data['key']
    iv = data['iv']
    ciphertext = data['ciphertext']

    cipher = Cipher(
        algorithms.AES(key),
        modes.CBC(iv),
        backend=default_backend()
    )
    decryptor = cipher.decryptor()

    decrypted_data = decryptor.update(ciphertext) + decryptor.finalize()
    return decrypted_data


# print(AES_Cipher_from_book())
